package com.mycjj.android;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap.CompressFormat;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ViewGroup;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.mycjj.android.db.CityAreaTable;
import com.mycjj.android.util.AppConfigs;
import com.mycjj.android.util.Preferences;
import com.mycjj.android.util.Utils;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

public class MyCjjApplication extends Application {
	public static final String NAME = "YourAppName";
	public static final String TAG = "YourAppName";
	public static final int MP = ViewGroup.LayoutParams.MATCH_PARENT;
	public static final int WC = ViewGroup.LayoutParams.WRAP_CONTENT;

	public static int addNewShow = 0; // 用于判断 主界面中的 添加item 下标new 是否显示 （0 ：
										// 不显示，1：显示）

	public boolean isAddCategorys;// 是否多次刷新
	public boolean isCateGoryFirstView;

	public static final int PRODUCT_LIST_TYPE_LIST = 0;
	public static final int PRODUCT_LIST_TYPE_BIG = 1;

	private DisplayMetrics dm = new DisplayMetrics();

	private static MyCjjApplication instance;

	private AlertDialog alertDialog;


	public static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
	// 用于保存当前 运行起来的 activity
	private List<String> activitys;
	private LocationClient mLocationClient;
	private LocationListener mMyLocationListener;
	private double latitude;// 纬度
	private double lontitude;// 经度
	private String nowAddress;//详细地址
	private String nowCity;//当前城市信息
	private int nowCityCodeId;

	@Override
	public void onCreate() {
		super.onCreate();
		instance = this;
		AppConfigs.initConfig(getContext());
		dm = getResources().getDisplayMetrics();
		initImageLoader();
		activitys = new ArrayList<String>();
		setSignState();
		init();
	}
	
	protected void setSignState(){
		String signDate = Preferences.getSharedPreferences(instance, "signDate", "1990-01-01");
		String currentDate  = Utils.getFormateDate(new Date(),"yyyy-MM-dd");
		if(currentDate.equals(signDate)){
			boolean isSign = Preferences.getSharedPreferences(instance, "isSign", false);
			Log.e("mark","signDate:"+signDate+";isSign:"+isSign);
		}else{
			Preferences.setEditor(instance, "isSign", false);
			Preferences.setEditor(instance, "signDate", currentDate);
		}
	}

	private void init() {
		mLocationClient = new LocationClient(getContext());
		LocationClientOption option = new LocationClientOption();
		option.setIsNeedAddress(true);
		mLocationClient.setLocOption(option);
		mMyLocationListener = new LocationListener();
		mLocationClient.registerLocationListener(mMyLocationListener);
		mLocationClient.start();
		mLocationClient.requestLocation();
	}
	
	@Override
	public void onTerminate() {
		super.onTerminate();
		if(mLocationClient != null){
			mLocationClient.stop();
		}
	}

	public class LocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// Receive Location
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());
			sb.append("\nerror code : ");
			sb.append(location.getLocType());
			latitude = location.getLatitude();
			sb.append("\nlatitude : ");
			sb.append(latitude);
			sb.append("\nlontitude : ");
			lontitude = location.getLongitude();
			sb.append(lontitude);
			sb.append("\nradius : ");
			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation) {
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
				sb.append("\ndirection : ");
				sb.append(location.getDirection());
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
				sb.append("\naddr : ");
				nowAddress = location.getAddrStr();
				sb.append(nowAddress);
				// 运营商信息
				sb.append("\noperationers : ");
				sb.append(location.getOperators());
			}
			nowCity = location.getCity();
//			mHander.sendEmptyMessage(0);
			Log.d("mark", "MyLocationListener:" + sb.toString());
		}

		@Override
		public void onReceivePoi(BDLocation arg0) {

		}
	}
	
	private Handler mHander = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 0:
				break;
			}
		}
	};

	public AlertDialog getAlertDialog() {
		return alertDialog;
	}

	public void setAlertDialog(AlertDialog ad) {
		this.alertDialog = ad;
	}

	public static MyCjjApplication getInstance() {
		return instance;
	}

	public static Context getContext() {
		return instance.getApplicationContext();
	}

	private ImageLoader imageLoader;

	private void initImageLoader() {
		imageLoader = ImageLoader.getInstance();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(instance)
				.memoryCacheExtraOptions(480, 800)
//				.discCacheExtraOptions(480, 800, CompressFormat.JPEG, 100)
				.threadPoolSize(5)
				.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
				.denyCacheImageMultipleSizesInMemory()
				.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
				.memoryCacheSize(2 * 1024 * 1024).discCacheSize(50 * 1024 * 1024)
				.discCacheFileCount(100)
				.defaultDisplayImageOptions(DisplayImageOptions.createSimple())
				.memoryCacheSize(2 * 1024 * 1024)
				.build();
		imageLoader.init(config);
	}

	public static File getStorageDir() {
		File file = Environment.getExternalStorageDirectory();
		return new File(file, MyCjjApplication.NAME);
	}

	public static boolean isStorageAvailable() {
		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
	}

	public static String makeUUIDString() {
		return UUID.randomUUID().toString();
	}

	public static SharedPreferences getSharedPreferences() {
		return PreferenceManager.getDefaultSharedPreferences(getContext());
	}

	public int dp2px(int dp) {
		return (int) (dp * getDisplayDensity() + 0.5f);
	}

	public int px2dp(int px) {
		return (int) (px / getDisplayDensity() + 0.5f);
	}

	public int pxToSp(int px) {
		return (int) (px / dm.scaledDensity);
	}

	public int spToPx(int sp) {
		return (int) (sp * dm.scaledDensity);
	}

	/**
	 * 获取 屏幕像素 px
	 * 
	 * @return Integer[高度，宽度]
	 */
	public int[] getDisplayHightAndWightPx() {
		return new int[] { dm.heightPixels, dm.widthPixels };
	}

	/**
	 * 获取 屏幕像素 dp
	 * 
	 * @return Integer[高度，宽度]
	 */
	public int[] getDisplayHightAndWightDp() {
		return new int[] { px2dp(getDisplayHightAndWightPx()[0]), px2dp(getDisplayHightAndWightPx()[1]) };
	}

	/**
	 * 获取像素密度
	 * 
	 * @return
	 */
	public float getDisplayDensity() {
		return dm.density;
	}

	public int getStatusBarHeight() {
		int result = 0;
		int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
		if (resourceId > 0) {
			result = getResources().getDimensionPixelSize(resourceId);
		}
		return result;
	}

	public boolean isConnect() {
		try {
			ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				NetworkInfo info = connectivity.getActiveNetworkInfo();
				if (info != null && info.isConnected()) {
					if (info.getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		} catch (Exception e) {

		}
		return false;
	}

	public boolean isAddCategorys() {
		return isAddCategorys;
	}

	public void setisAddCategorys(boolean isAddCategorys) {
		this.isAddCategorys = isAddCategorys;
	}

	public boolean isCateGoryFirstView() {
		return isCateGoryFirstView;
	}

	public void setCateGoryFirstView(boolean isCateGoryFirstView) {
		this.isCateGoryFirstView = isCateGoryFirstView;
	}

	// public void checkNewVersion(final Context context){
	// httpRequestImpl.Update(httpRequestImpl.VERSION_UPDATE, new
	// AsyncHttpResponseHandler(){
	// @Override
	// public void onSuccess(String content) {
	// super.onSuccess(content);
	// SonyDataManage sonyDataInstance = SonyDataManage.getInstance();
	// final SonyUpdate sonyUpdates = sonyDataInstance.getUpdateList();
	// if(sonyUpdates.getLatest_version().equals(getVersion(context))){
	// Toast.makeText(context, "当前版本已经是最新版本", Toast.LENGTH_SHORT).show();
	// }else{
	// AlertDialog.Builder build = new AlertDialog.Builder(context);
	// build.setTitle("新版本");
	// build.setMessage(sonyUpdates.getFeatures());
	// build.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
	// @Override
	// public void onClick(DialogInterface arg0, int arg1) {
	// Intent intent = new Intent(context,SonyWebViewActivity.class);
	// intent.putExtra("webViewUrl", new String[]{"1",sonyUpdates.getLink()});
	// context.startActivity(intent);
	// }
	// }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	//
	// }
	// });
	// build.create().show();
	// }
	// }
	// });
	// }

	public List<String> getActivitys() {
		return activitys;
	}

	public void setActivitys(List<String> activitys) {
		this.activitys = activitys;
	}

	public void addActivityName(String activityName) {
		if (null != activityName && !"".equals(activityName))
			activitys.add(activityName);
	}

	public void removeActivityName(String activityName) {
		if (null != activityName && !"".equals(activityName)) {
			for (int i = 0; i < activitys.size(); i++) {
				if (activityName.equals(activitys.get(i))) {
					activitys.remove(i);
					return;
				}
			}
		}
	}

	public String getVersion(Context context) {
		String version = null;
		try {
			PackageManager manager = context.getPackageManager();
			PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
			version = info.versionName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return version;
	}

	public static boolean isWorked() {
		ActivityManager myManager = (ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE);
		ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager.getRunningServices(50);
		for (int i = 0; i < runningService.size(); i++) {
			Log.i("info", "-----------------service.getClassName().toString()==" + runningService.get(i).service.getClassName().toString());
			if (runningService.get(i).service.getClassName().toString().equals("com.sony.store.china.application.UpdateService")) {
				return true;
			}
		}
		return false;
	}

	public ImageLoader getImageLoader() {
		return imageLoader;
	}

	public void setImageLoader(ImageLoader imageLoader) {
		this.imageLoader = imageLoader;
	}

	public String getPoints() {
		//经度在前，纬度在后
		Log.e("mark", "getPoints():"+(lontitude +","+latitude));
		return lontitude +","+latitude;
	}

	public double getLatitude() {
		return latitude;
	}

	public double getLontitude() {
		return lontitude;
	}

	public String getNowAddress() {
		return nowAddress;
	}
	public String getNowCity() {
		return nowCity;
	}

	public int getNowCityId() {
//		nowCityCodeId = CityAreaTable.getCityId(nowCity);
		if(nowCityCodeId == 0){
			nowCityCodeId = 175;
		}
//		return nowCityCodeId;
		return 175;
	}
	
	
	

}
